package com.cgy.utils.spider.spider;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import com.cgy.utils.spider.callback.AbstractCallBack;
import com.cgy.utils.spider.setting.Setting;
import com.cgy.utils.spider.template.Template;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author CHTK
 */
@NoArgsConstructor
@Slf4j
public abstract class AbstractSpider {

    protected Setting setting;
    protected List<Template> template = Lists.newArrayList();
    protected AbstractCallBack abstractCallBack;


    /**
     * 设置
     * @param setting
     * @return
     */
    public AbstractSpider setting(Setting setting) {
        this.setting = setting;
        return this;
    }

    public AbstractSpider template(String json) {
        Gson gson = new GsonBuilder().serializeNulls().create();
        Template template = gson.fromJson(json, Template.class);
        this.template.add(template);
        return this;
    }

    public AbstractSpider template(Template template, Template... other) {
        this.template.add(template);
        for (Template template1 : other) {
            this.template.add(template1);
        }
        return this;
    }

    public AbstractSpider template(Template template) {
        this.template.add(template);
        return this;
    }

    public AbstractSpider template(File file, File... files) {
       template(file);
        for (File file1 : files) {
            template(file1);
        }
        return this;
    }

    public AbstractSpider template(File file) {
        try (FileInputStream fileInputStream = FileUtils.openInputStream(file)) {
            JAXBContext jaxbContext = JAXBContext.newInstance(Template.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            Object unmarshal = unmarshaller.unmarshal(fileInputStream);
            this.template.add((Template) unmarshal);
        } catch (IOException e) {
            log.error("file open exception");
            e.printStackTrace();
        } catch (JAXBException e) {
            log.error("template unmarshal exception");
            e.printStackTrace();
        }
        return this;
    }
    /**
     * 启动
     * @param abstractCallBack
     */
    abstract public void start(AbstractCallBack abstractCallBack);

    /**
     * 启动
     */
    abstract public void start();

    /**
     * 停止
     */
    abstract public void stop();

    /**
     *
     * @return
     */
    public static AbstractSpider build() {
        return null;
    };

}


